package de.unimannheim.ki.servlets;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;



import de.unimannheim.ki.usermanagement.FacebookSessionHandler;

import de.unimannheim.ki.usermanagement.UserManager;

/**
 * Servlet implementation class MainServer
 */

public class MainServer extends HttpServlet {
	private Gson gson;
	private FacebookSessionHandler fbSessionHandler;
	private static final long serialVersionUID = 1L;
	private WebServiceClient wscl; 
	private UserManager userManager;
	
	//Session attributes
	public static final String FBUSER = "FBUSER";
	public static final String SESSIONATTRI= "accessToken";


	  
	@Override
	public void init() throws ServletException {
		super.init();
		ServletContext sc = this.getServletContext();
		gson = new Gson();
		wscl = new WebServiceClient();
		userManager = new UserManager();
		fbSessionHandler = new FacebookSessionHandler();
		
	}
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MainServer() {
        super();
     
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		HttpSession usersession;
		if(request.getSession(false) == null){
		
			 usersession = request.getSession(true);
		} else {
			usersession = request.getSession(false);
		}
		
		
		if( usersession.getAttribute("accessToken") != null){
			System.out.println("there is a acess Token for this Session");
		}
		if(request.getParameter("musicuser") != null){
			usersession.setAttribute("USER", request.getParameter("musicuser"));
		}
		if(request.getParameter("endsession") != null){
			 System.out.println("test");
			 usersession.invalidate();
			
			 
			response.sendRedirect("http://"+request.getServerName()+":"+request.getServerPort()+FacebookSessionHandler.APPADRESSShort);
		} else {
			
			// for acess token handling
				Map<String, String[]> paramMap = null;
				paramMap = request.getParameterMap();
				if(fbSessionHandler.userisLoggedIn(usersession)){
					System.out.println("User is Logged In!!!");
					if(userManager.isregistered(fbSessionHandler.getAccessToken(usersession))){
						// Do further process
						// redirect to data page
						System.out.println("user is registred");
						//establish data service
						if(paramMap.containsKey("service")) {
							System.out.println("service entered1");
							
							//Get Songs Service
							if (request.getParameter("service").equals("songs")) {
								//default algorithm
								int algorithm = UserManager.LIKEJOINT;
								if( request.getParameter("method")!= null){
									//get specified alogrithmn
									algorithm = Integer.parseInt(request.getParameter("method"));
								} 
								PrintWriter pw = new PrintWriter(response.getOutputStream());
								if(request.getParameter("start") != null 
										&& request.getParameter("offset")!= null
										&& request.getParameter("threshold")!= null){
									int start = Integer.parseInt(request.getParameter("start"));
									int offset = Integer.parseInt(request.getParameter("offset"));
									double threshold = Double.parseDouble(request.getParameter("threshold"));
					
									pw.print(userManager.getJSONStringforUsers((String)usersession.getAttribute("FBUSER"), algorithm, start, offset, threshold));
								}else {
									pw.print(new JsonAnswer(1, null,JsonError.generateParameterMissing(),0));
								}
								pw.flush();
								pw.close();
								//response.
							} else if (request.getParameter("service").equals("evaluate")){
								// Evaluate Songs Service
								System.out.println("Evaluate Service started");
								String jsondata = request.getParameter("data");
								//User to save
								String saveuser = (String) usersession.getAttribute(MainServer.FBUSER);
								
								JsonEvaluateAnswer jsonanswer = gson.fromJson(jsondata , JsonEvaluateAnswer.class);
								userManager.persistRating(saveuser, jsonanswer);
								PrintWriter pw = new PrintWriter(response.getOutputStream());
								pw.println(new JsonAnswer(0, null,null,0) );
								pw.flush();
								pw.close();
							}else if (request.getParameter("service").equals("reload")){
								userManager.refreshRegisteredUser( (String) usersession.getAttribute("accessToken") );
								
							}
						}else {
							response.sendRedirect("music.jsp");
						}
					} else {
						
						//verify if the lastfm user name is set
						System.out.println("register user");
						if(usersession.getAttribute("USER") != null){
							if(usersession.getAttribute("USER").equals("alexmueller89")){
								userManager.registerUser(fbSessionHandler.getAccessToken(usersession), "alexmueller89");
							}else{
								userManager.registerUser(fbSessionHandler.getAccessToken(usersession), (String)usersession.getAttribute("USER"));
							}
							response.sendRedirect("start");
						} else {
							response.sendRedirect("signup.jsp?errorcode=1");
						}
					
						
					}
				}else{
					if(paramMap.containsKey("service")) {
						System.out.println("service entered1");
						if (request.getParameter("service").equals("songs")) {
							System.out.println("service error entered");
							
							JsonAnswer ja = new JsonAnswer(1, null, JsonError.generateNotLoggedIn(),0);
							PrintWriter pw = new PrintWriter(response.getOutputStream());
							pw.print(ja.getJsonString());
							pw.flush();
							pw.close();
							//response.
						}
					} else {
						
						fbSessionHandler.handleLogFlow(usersession,request.getServerName(), request.getServerPort()+"", request.getLocalAddr(), response, wscl, paramMap);
					}
				}// user register if end
		}// usersession if end
	}//doGet end
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	}

}
